import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import cookie from 'js-cookie'

// 创建axios实例
const service = axios.create({
    //baseURL: 'htpp://localhost:8201', //api的base url
    //baseURL: 'http://localhost:9001', //nginx
    //baseURL: 'http://localhost:8222', //gateway网关
    baseURL: 'http://localhost:8222',
    timeout: 15000 //请求超时时间
})

// http request拦截器
service.interceptors.request.use(
    config => {
        // debuger
        console.log('request拦截器部分')
        console.log(config)
        console.log('request拦截器'+cookie.get('education_token'))
        if(cookie.get('education_token')){
            config.headers['token'] = cookie.get('education_token')
        }
        // 设置请求后端headers编码，使得一致后，后端接受数据不多=符号
        config.headers['Content-Type']='application/json';
        return config
    },
    err => {
        return Promise.reject(err);
    }
)

// http response拦截器
service.interceptors.response.use(
    response => {
        console.log('response拦截部分')
        console.log(response)
        //debugger
        if(response.data.code == 28004) {
            console.log('code是28004')
            //debugger
            window.location.href= '/login'
            return;
        }else{
            if(response.data.code !== 20000){
                //25000: 表示订单支付中，不做任何提示
                if(response.data.code != 25000){
                    Message({
                        message: response.data.message || 'error',
                        type: 'error',
                        duration: 5*1000
                    })
                }
            }else{
                return response;
            }
        }
    },
    error => {
        // 返回接口返回的错误信息
        return Promise.reject(error.response)
    }
)

export default service